<template>
  <div>
    <!-- <dialog-comp v-if="showDialog" :v-show-dialog.sync="showDialog" @dialogClose="dialogClose" ref="dialog"></dialog-comp> -->
    <modify-dialog-comp v-if="showDialogModify" :show-child-dialog.sync="showDialogModify" ref="dialogmodify" @modifyFlush="flushTable"></modify-dialog-comp>
    <add-dialog-comp v-if="showDialogAdd" :show-child-dialog.sync="showDialogAdd" ref="dialogadd" @addFlush="flushTable"></add-dialog-comp>
    <t-form
      ref="form"
      :data="formData"
      :label-width="80"
      colon
      @reset="onReset"
      @submit="onSubmit"
      :style="{ marginBottom: '8px' }"
    >
      <t-row style="margin-top: 20px;">
            <t-col >
              <t-form-item name="task_name">
                <t-input
                  v-model="formData.task_name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入关键字"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }">查询</t-button>
              <t-button type="reset" variant="base" theme="default">重置</t-button>
            </t-col>
      </t-row>
      <t-row>
        <t-col class="operation-ad-container">
          <t-button @click="handleCreatTask" theme="primary" > 新增请求 </t-button>
          <t-button @click="handleDeleteTask" variant="base" :style="{ marginLeft: '8px'}" theme="default" :disabled="!selectedRowKeys.length"> 删除请求 </t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <t-table
        :data="data"
        :columns="columns"
        rowKey="id"
        :verticalAlign="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="rehandleSelectChange"
        :loading="dataLoading"
        :headerAffixedTop="true"
        :headerAffixProps="{ offsetTop, container: getContainer }"
      >
      <template #status="row">
        <p class="status" :class="['', 'warning', 'unhealth'][row.con_state]">
              {{ ['健康', '警告', '异常'][row.con_state] }}
            </p>
          <!-- <t-tag v-if="row.status === CASE_STATUS.INIT" theme="danger" variant="light">未执行</t-tag>
          <t-tag v-if="row.status === CASE_STATUS.RUN" theme="warning" variant="light">执行中</t-tag>
          <t-tag v-if="row.status === CASE_STATUS.SUCCESS" theme="warning" variant="light">成功</t-tag>
          <t-tag v-if="row.status === CASE_STATUS.FAIL" theme="success" variant="light">失败</t-tag> -->
      </template>
        <template #op="slotProps">
          <!-- <a class="t-button-link" @click="handleClickConn(slotProps)">连接</a> -->
          <a class="t-button-link" @click="handleClickModify(slotProps)">编辑</a>
          <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>          
        </template>
      </t-table>

      <t-dialog
        header="确认删除当前所选任务？"
        :body="confirmBody"
        :visible.sync="confirmVisible"
        @confirm="onConfirmDelete"
        :onCancel="onCancel"
        @deleteFlush="flushTable"
      >
      </t-dialog>
    </div>
  </div>
  
</template>
<script lang="jsx">
import Vue from 'vue';
import { prefix } from '@/config/global';
// import Trend from '@/components/trend/index.vue';
import modifyDialogComp from './ModifyDialogComp.vue';
import addDialogComp from './AddDialogComp.vue';
// import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon} from 'tdesign-icons-vue';
import { getUserList } from '@/api/requestApi';
import { TASK_LIST } from '@/service/service-detail'


const INITIAL_FORM_DATA = {
  task_name: '',
  testplan_name: '',
  chain_name: '',
  create_user: '',
  custom_type: '',
};

export default {
  name: 'list-table',
  
  components:{
    modifyDialogComp,
    addDialogComp,
  },
  inject: ['reload'],
  data() {
    return {
      prefix,
      userList:[],
      formData: {...INITIAL_FORM_DATA},
      data: [],
      selectedRowKeys: [],
      dataLoading: false,
      value: 'first',
      columns: [
        { colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left' },
        {
          title: 'ID',
          fixed: 'left',
          width: 50,
          align: 'left',
          ellipsis: true,
          colKey: 'id',
        },
        {
          title: '请求名称',
          width: 100,
          ellipsis: true,
          colKey: 'request_name',
        },
        {
          title: '链名称',
          width: 50,
          ellipsis: true,
          colKey: 'chain_name',
        },
        {
          title: '虚拟机名称',
          width: 80,
          ellipsis: true,
          colKey: 'testplan_name',
        },
        {
          title: '合约名称',
          width: 80,
          ellipsis: true,
          colKey: 'contr_name',
        },
        {
          title: '合约方法',
          width: 80,
          ellipsis: true,
          colKey: 'contr_type',
        },
        { 
          title: '创建人', 
          colKey: 'creator',
          align: 'left', 
          width: 50, 
        },
        {
          title: '创建时间',
          width: 100,
          ellipsis: true,
          colKey: 'start_time',
        }, 
        {
          align: 'left',
          fixed: 'right',
          width: 100,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'index',
      tableLayout: 'auto',
      verticalAlign: 'top',
      showDialogModify: false, // 控制弹窗的现实与隐藏
      showDialogAdd: false, // 控制弹窗的现实与隐藏
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      deleteIdx: -1,
      deleteChainName: '',
    };
  },
  computed: {
    confirmBody() {
      if (this.deleteIdx > -1) {
        return '任务将被删除，删除后无法恢复';
      }
      return '批量删除后将无法恢复';
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
  },
  mounted() {
    this.dataLoading = true;
    const params = {
        params: {
          page: this.pagination.defaultCurrent,
          per_page: this.pagination.defaultPageSize,
        },
      };
    this.$request.get("/api/performance/chain/config/list", params).then((res) => {
      this.dataLoading = false;
      if (res.code === 0) {
        const { list = [] } = res.data;
        console.log(res.data)
        this.data = list;
        this.pagination = {
          ...this.pagination,
          total: list.length,
        };
      }
    })

  },
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    onReset() {
      this.formData.chain_name = '';
      this.formData.task_name = '';
      this.formData.testplan_name = '';
      this.formData.create_user = '';
    },
    onSubmit() {
    },
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    rehandleSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      console.log(selectedRowKeys);
    },
    
    addOrUpdateRefresh() {
      console.log("text, row");
    },
    handleClickModify(slotProps) {
      this.showDialogModify = true;
      this.$nextTick(()=>{
      // 调用的是d子组件里面的init方法传递行数据      
        this.$refs.dialogmodify.init(slotProps.row);
      })
    },
    // 关闭弹窗组件
    dialogClose() {
      this.showDialogModify = true
    },
    handleCreatTask() {
      this.$router.push('/request/add');
    },
    handleClickDelete(slotProps) {
      this.deleteIdx = slotProps.row.id;
      this.deleteChainName = slotProps.row.name;
      console.log("打印下单选",this.deleteIdx,slotProps)
      this.confirmVisible = true;
    },
    handleDeleteTask() {
      this.confirmVisible = true;

    },
    onConfirmDelete() {
      // 真实业务请发起请求
      let ids = [];
      const reqParam = {"ids": [], "param": {}, "op_type": ''};
      this.confirmVisible = false;
      // console.log("打印下单选deleteIdx",this.deleteIdx)
      if (this.deleteIdx > -1){
        ids.push(this.deleteIdx)
        // console.log("打印下单选ids",ids)
      } else {
        ids = Array.from(Object.values(this.selectedRowKeys), x=>x);
        // ids = Object.values(this.selectedRowKeys)
        // console.log("打印下多选ids",ids)
      }
      this.ids = ids.map(String)
      reqParam.op_type = 0;
      reqParam.ids = this.ids;
     
      this.flushTable();
      this.resetIdx();
    },
    // 获取创建人
    getUserList(){
      getUserList()
        .then((res) => {
          if (res.data.code === '000') {
            const list = res.data.data;      
            this.userList = list;
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    handleChangeCreateUser(...args) {
      console.log('change', ...args);
    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = -1;
    },
    closeConn() {
      this.chainConn = false;
    },
    closeLog() {
      this.chainConnLog = false;
    },
    // sleep
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    async flushTable(){
      await this.sleep(1000)
      this.reload();
    }
    // 处理字典
    // mapData(data) {
    //   const mappedData = { ...data };
    //   const sexMap = { '1': '男', '2': '女' };
    //   const typeMap = { '1': '类型1', '2': '类型2', '3': '类型3' };
    //   mappedData.sex = sexMap[data.sex];
    //   mappedData.type = typeMap[data.type];

    //   return mappedData;
    // }
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.form-item-content {
  width: 400px;
}

.selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-s);
    color: var(--td-text-color-secondary);
  }
.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operation-ad-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 20px 0;
}
</style>
